{extend name="main"}
{block name="style"}
<style type="text/css">
    .flex-lable {
        width: 120px;
        color: #6c757d;
        text-align: right;
        padding-right: 10px;
    }

    .el-image-viewer__img {
        transition: all .3s;
        -moz-transition: all .3s;
        -webkit-transition: all .3s;
        -o-transition: all .3s;
    }

    .w-400px {
        width: 400px !important;
    }

    .status {
        position: absolute;
        right: 5px;
        top: 5px;
        background-color: #FFF;
        border: solid 1px #FF6D06;
        color: #FF6D06;
        width: 60px;
        height: 20px;
        line-height: 18px;
        text-align: center;
        border-radius: 10px;
        z-index: 100;
    }

    .status.success {
        border: solid 1px #28a745;
        color: #28a745;
    }

    .status.danger {
        border: solid 1px #dc3545;
        color: #dc3545;
    }

    .checkbox-id {
        position: absolute;
        left: 5px;
        top: 5px;
    }

    .checkbox-id .el-checkbox__label {
        display: none;
    }
</style>
{/block}
{block name="body"}
<div class="bg-white p-3">
    <div class="table-responsive py-3 flex">
        <el-upload ref="upload" :file-list="fileList" :show-file-list="false" :auto-upload="false" :multiple="false"
            :on-change="readXlsx">
            <el-button slot="trigger" type="primary" size="mini">
                导入({{tableData.length}})
            </el-button>
        </el-upload>

        <el-button type="success" size="mini" @click="submitJobs" plain style="margin-left: 10px;">批量提交</el-button>
        <el-button type="info" size="mini" @click="showSuccessNumber" plain>
            可导入：(<span>{{effectiveNumber}}</span>)&nbsp;|&nbsp;已成功：(<span>{{successNumber}}</span>)
        </el-button>
    </div>
    <div class="table-responsive py-3 flex">导入模板及注意事项请&nbsp;<a target="_blank"
            href="https://www.xycms.com/contact_us.html">联系客服领取</a></div>
    <div class="table-responsive">
        <el-table ref="tableList" :data="tableData" style="width: 100%;" header-cell-class-name="table-header-DDE6FB"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" :selectable="checkSelectable">
            </el-table-column>
            <el-table-column label="详情" width="50">
                <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" :content="scope.row.errMsg ? scope.row.errMsg : '此数据有效'"
                        placement="top-start">
                        <i v-if="scope.row.invalid" class="el-icon-warning pointer text-danger h5 mb-0"></i>
                        <i v-else-if="!scope.row.invalid&&scope.row.errMsg"
                            class="el-icon-question pointer text-warning h5 mb-0"></i>
                        <i v-else class="el-icon-success pointer text-success h5 mb-0"></i>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column label="职位名称/发布企业" width="260">
                <template slot-scope="scope">
                    <div>
                        {{scope.row.job_name}}
                        <br />
                        {{scope.row.company_name}}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="企业认证" width="160">
                <template slot-scope="scope">
                    <div>
                        <span v-if="scope.row.attestation == null">未对此数据进行验证</span>
                        <span v-else-if="scope.row.attestation == '已认证'" class="text-success">已认证</span>
                        <span v-else class="text-danger">未认证</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="薪资待遇">
                <template slot-scope="scope">
                    <div v-if="scope.row.salary_range">
                        {{scope.row.salary_min}}k-{{scope.row.salary_max}}k&nbsp;|&nbsp;{{scope.row.salary_year}}薪
                    </div>
                    <div v-else>
                        面议&nbsp;|&nbsp;{{scope.row.salary_year}}薪
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="工作地区">
                <template slot-scope="scope">
                    <div>
                        {{scope.row.jobs_area1}}/{{scope.row.jobs_area2}}/{{scope.row.jobs_area3}}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="工作性质" width="80">
                <template slot-scope="scope">
                    <div>
                        {{scope.row.job_type}}
                    </div>
                </template>
            </el-table-column>
        </el-table>
    </div>
</div>
{/block}

{block name="script"}
{js href="__PLUGIN_SRC__/Xlsx/xlsx.core.min.js"}
{js href="__PLUGIN_SRC__/Xlsx/xlsx.utils.min.js"}

<script type="text/javascript">
    var hwdn = null;
    var vm = new Vue({
        el: '#app',
        data: {
            view: XYBase.view,
            labelPosition: 'right',
            showLog: false,
            dialogVisible: false,
            successNumber: 0,
            tableData: [],
            fileList: [],
            fileReader: {}
        },
        watch: {
            view: XYBase.viewWatch,
        },
        computed: {
            effectiveNumber() {
                let result = 0;
                for (let i = 0; i < this.tableData.length; i++) {
                    if (this.tableData[i].invalid != undefined && this.tableData[i].invalid == false) {
                        result++;
                    }
                }
                return result;
            }
        },
        created() {
            XYBase.created(this);
        },
        methods: {
            handleSelectionChange() {

            },
            readXlsx(e) {
                let _this = this;
                file = e.raw;
                let fileReader = new FileReader();

                fileReader.onload = function (ev) {
                    try {
                        var data = ev.target.result,
                            // 以二进制流方式读取整份excel表格对象
                            workbook = XLSX.read(data, {
                                type: 'binary'
                            });
                    } catch (e) {
                        XYBase.error('文件类型不正确');
                        return;
                    }

                    // 表格的表格范围，可用于判断表头是否数量是否正确
                    let fromTo = '';
                    /* 
                      遍历每张工作表
                      sheet是Sheets这个对象属性的key，Sheets则是Excel文件中所有的工作表(每个工作表则是这个对象的属性)
                    */

                    _this.tableData = [];
                    for (let sheet in workbook.Sheets) {
                        // 获取表头最后一列的坐标
                        fromTo = workbook.Sheets[sheet]['!ref'];
                        // 获取出表格中(不为空)的数据，属性名则是表头的对应列
                        let content = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
                        for (let index = 0; index < content.length; index++) {
                            let row = _this.buildJobData(content[index]);
                            _this.tableData.push(row)
                        }
                        // 只读取第一个工作表，所以只循环一次
                        break;
                    }
                    // 通过接口校验读取出来的数据
                    _this.checkAllData()
                };
                fileReader.readAsBinaryString(file);
            },
            buildJobData(row) {
                // 开始初步校验
                let data = {
                    invalid: false,
                    errMsg: '',
                    attestation: null
                };
                try {
                    if (row['企业用户手机号'] == undefined) {
                        throw '企业用户手机号不能为空';
                    } else {
                        data.company_mobile = row['企业用户手机号'];
                    }
                    if (row['企业名称'] == undefined) {
                        throw '企业名称不能为空';
                    } else {
                        data.company_name = row['企业名称'];
                    }
                    if (row['职位名称'] == undefined) {
                        throw '职位名称不能为空';
                    } else {
                        data.job_name = row['职位名称'];
                    }
                    if (row['工作性质'] != undefined) {
                        data.job_type = row['工作性质'];
                    }
                    if (row['工作地区'] == undefined) {
                        throw '工作地区不能为空';
                    } else {
                        let area = row['工作地区'].split('>');
                        if (area.length < 3) {
                            throw '工作地区格式错误';
                        }
                        data.jobs_area1 = area[0];
                        data.jobs_area2 = area[1];
                        data.jobs_area3 = area[2];
                    }
                    if (row['薪资待遇'] == undefined) {
                        throw '薪资待遇不能为空';
                    } else {
                        let salary = row['薪资待遇'].split('-');
                        let regex = /[0-9]{1,3}/;

                        if (salary.length < 2) {
                            data.salary_min = '面议';
                            data.salary_max = '面议';
                            data.salary_range = false;
                        } else {
                            data.salary_min = Number(salary.length < 2 ? 0 : regex.test(salary[0]) ? regex.exec(salary[0])[0] : 0);
                            data.salary_max = Number(salary.length < 2 ? 100 : regex.test(salary[1]) ? regex.exec(salary[1])[0] : 100);
                            data.salary_range = true;
                        }
                    }
                    if (row['薪资类型'] != undefined) {
                        data.salary_year = 12;
                    } else {
                        let regex = /[0-9]{1,3}/;
                        data.salary_year = regex.exec(row['薪资类型'])[0] ? regex.exec(row['薪资类型'])[0] : 12;
                    }
                    if (row['学历要求'] == undefined) {
                        data.education_level = '学历不限';
                    } else {
                        data.education_level = row['学历要求'];
                    }
                    if (row['经验要求'] == undefined) {
                        data.education_level = '经验不限';
                    } else {
                        data.education_level = row['经验要求'];
                    }
                    if (row['需求人数'] == undefined) {

                    } else {
                        data.number_of_recruits = (Number)(row['需求人数']);
                    }
                    if (row['职位类别'] == undefined) {
                        throw '职位类别不能为空'
                    } else {
                        let cates = row['职位类别'].split('>');
                        if (cates.length < 3) {
                            throw '职位类别格式错误';
                        }
                        data.jobs_cate1 = cates[0];
                        data.jobs_cate2 = cates[1];
                        data.jobs_cate3 = cates[2];
                    }
                    if (row['职位详情'] == undefined) {
                        data.jobs_desc = '';
                    } else {
                        data.jobs_desc = row['职位详情'];
                    }
                    if (row['职位联系人'] == undefined) {
                        throw '职位联系人不能为空';
                    } else {
                        data.contacts = row['职位联系人'];
                    }
                    if (row['职位联系电话'] == undefined) {
                        data.contacts_mobile = '';
                    } else {
                        let regex = /1[1-9][0-9]{9}/g
                        data.contacts_mobile = regex.exec(row['职位联系电话'])[0];
                    }
                    if (row['固定电话'] == undefined) {
                        data.contacts_tel = '';
                    } else {
                        data.contacts_tel = row['固定电话'];
                    }
                    if (row['详细地址'] == undefined) {
                        throw '详细地址不能为空';
                    } else {
                        data.contacts_address = row['详细地址'];
                    }
                    if (row['使用企业联系方式'] == undefined) {
                        data.contacts_type = 0;
                    } else {
                        data.contacts_type = row['使用企业联系方式'] == 'Y';
                    }
                } catch (ex) {
                    console.log(ex);
                    data.invalid = true;
                    data.errMsg = ex;
                }
                console.log(data);
                return data;
            },

            checkSelectable(row, index) {
                let result = true;
                if (row.invalid == undefined || row.invalid) {
                    result = false;
                }
                return result;
            },
            checkAllData() {
                let _this = this;
                hwdn = XYBase.openloading('数据核验中，请勿刷新网页或关闭浏览器');
                this.checkDataAjax(0);
            },
            checkDataAjax(i) {
                let _this = this;
                let target = _this.tableData[i];
                if (!target) return hwdn.close();
                i++;
                if (target.invalid) {
                    return _this.checkDataAjax(i);
                }
                $.ajax({
                    url: '/jobs/verify',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(target),
                    success(res) {
                        if (res.code != undefined && res.code == 0) {
                            target.attestation = res.data.attestation;
                            target.invalid = false;
                        } else {
                            target.invalid = true;
                            target.errMsg = res.msg ?? '网络错误';
                        }
                        _this.checkDataAjax(i);
                    },
                    error() {
                        _this.checkDataAjax(i);
                    }
                });
            },
            showErrorReason(row) {
                console.log(row.errMsg)
            },
            submitJobs() {
                let _this = this;
                for (let i = 0; i < _this.tableData.length; i++) {
                    $.ajax({
                        url: '/jobs/importJobs',
                        type: 'POST',
                        contentType: 'application/json;charset=utf-8;',
                        data: JSON.stringify(_this.tableData[i]),
                        success(res) {
                            if (res.code != undefined) {
                                if (res.code == 0) {
                                    _this.successNumber++;
                                } else {
                                    _this.tableData[i].invalid = true;
                                    _this.tableData[i].errMsg = res.msg;
                                }
                            } else {
                                _this.tableData[i].errMsg = '网络错误';
                            }
                        }
                    })
                }
            },
            showSuccessNumber() {
                XYBase.msg(`本次已成功导入${this.successNumber}份职位`);
            },
            initHtml() {
                this.fileReader = new FileReader();
            },
        },
        mounted() {
            this.initHtml()
        },
    });
    $(function () {
        reloadWindowSize();
        $(window).resize(function () {
            reloadWindowSize();
        });
    });
    function reloadWindowSize(argument) {
        var winW = $(window).width();
        if (winW <= 576) {
            vm.labelPosition = 'top';
        } else {
            vm.labelPosition = 'right';
        }
    }
</script>
{/block}